<template>
	<view class="container">
		<!-- 地图部分 - 调整为50%高度 -->
		<map id="myMap" class="map-container" :latitude="latitude" :longitude="longitude" :markers="covers"
			@markertap="markertap" @bindregionchange="handleScaleChange" :show-location="showUserLocation"
			:scale="scale" @regionchange="handleScaleChange" :show-scale="true" :max-scale="18" :min-scale="5">
			<!-- 地图右下角控制按钮 - 调整了垂直间距 -->
			<cover-view class="map-controls">
				<cover-view class="control-btn" @tap="locateMe">
					<cover-image src="/static/mylocation.png"></cover-image>
				</cover-view>
				<cover-view class="control-btn" @tap="zoomIn">
					<cover-image src="/static/zoom-in.png"></cover-image>
				</cover-view>
				<cover-view class="control-btn" @tap="zoomOut">
					<cover-image src="/static/zoom-out.png"></cover-image>
				</cover-view>
			</cover-view>
			<!-- 调整显示列表方法 -->
			<cover-view class="list-btn-container" @tap="toggleStationList">
				<cover-view class="list-btn">
					<cover-image src="/static/list-icon.png"></cover-image>
				</cover-view>
			</cover-view>
		</map>
		<!-- 场站列表区域 -->
		<view class="station-list-container" v-if="showStationList">
			<view class="list-header">
				<text class="list-title">附近充电站</text>
				<text class="list-count">共{{stationList.length}}个</text>
			</view>
			<scroll-view class="station-scroll" scroll-y>
				<view class="station-list">
					<view class="station-item" v-for="station in stationList" @click="stationClick(station.stationId)"
						:key="station.stationId">
						<view class="station-main">
							<view class="station-info">
								<text class="station-name">{{station.stationName}}</text>
								<text class="station-address">{{station.address}}</text>
								<view class="station-tags">
									<text class="tag">促销</text>
									<text class="tag">自营</text>
									<text class="tag">直流</text>
								</view>
							</view>
							<view class="station-distance">
								<text class="distance-value">{{station.distance}}km</text>
								<image class="nav-icon" src="/static/to-detail@2x.png"></image>
							</view>
						</view>
						<view class="station-footer">
							<text class="price-text">1.5元/度</text>
							<text class="status-text">{{station.stationStatus === 0 ? '营业中' : '未营业'}}</text>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>
		<!-- 充电站信息弹窗 -->
		<zwy-popup :ishide='isshow' width="350px" height="180rpx" radius="16rpx">
			<view class="popup-content">
				<view class="station-info">
					<image class="station-icon" src="../../static/station-icon@2x.png"></image>
					<view class="info-detail">
						<view class="station-name">
							<cover-view>{{mapClickStation.stationName || '充电站'}}</cover-view>
							<cover-view>{{mapClickStation.stationStatus === 0 ? '营业中' : mapClickStation.stationStatus === 1 ? '未营业' : '未知'}}</cover-view>
							<cover-view class="price">1.50元/度</cover-view>
						</view>
						<view class="line-space"></view>
						<view class="station-meta">
							<view class="distance">
								<image class="map-icon" src="../../static/nearby_normal@2x.png"></image>
								<cover-view>距离您{{mapClickStation.distance || '--'}}KM</cover-view>
							</view>
							<view class="go-charging" @click="stationClick(mapClickStation.stationId)">详情</view>
						</view>
					</view>
				</view>
			</view>
			<!-- 关闭按钮 -->
			<view class="close-btn" @click="isshow=false">✕</view>
		</zwy-popup>
	</view>

</template>

<script>
	export default {
		data() {
			return {
				showUserLocation: false,
				latitude: 39.909,
				longitude: 116.39742,
				covers: [],
				stationList: [],
				mapClickStation: {},
				isshow: false,
				userLocationMarker: null,
				minRadius: 500,
				maxRadius: 50000,
				scale: 16,
				// 缩放级别与半径的映射关系
				scaleRadiusMap: {
					18: 500, // 最大缩放级别 - 最小半径
					17: 1000,
					16: 2000,
					15: 3000,
					14: 5000,
					13: 8000,
					12: 12000,
					11: 16000,
					10: 20000,
					9: 30000,
					8: 40000,
					7: 50000, // 最小缩放级别 - 最大半径
					// 更小的缩放级别使用最大半径
				},
				userLocation: { // 新增用户位置数据
					latitude: 39.90883,
					longitude: 116.39747,
				},
				currentRadius: 1000,
				isMapMoving: false, // 防止频繁请求
				debounceTimer: null,
				showStationList: true // 新增控制列表显示的状态
			}
		},
		onLoad() {
			this.initLocation();
		},
		methods: {
			zoomOut() {
				uni.showModal({
					content: "功能开发中",
					showCancel: false,
					confirmText: "知道了"
				})
			},

			zoomIn() {
				uni.showModal({
					content: "功能开发中",
					showCancel: false,
					confirmText: "知道了"
				})
			},
			locateMe() {
				uni.showLoading({
					title: '定位中...'
				});
				// 1. 创建地图上下文
				const mapCtx = uni.createMapContext("myMap", this);
				// 3. 使用地图API移动视图
				mapCtx.moveToLocation({
					latitude: this.latitude,
					longitude: this.longitude,
					duration: 500,
					success: () => {
						console.log("地图移动成功");
						// 4. 更新用户位置标记
						this.updateUserLocationMarker();
						// 5. 重新加载附近站点
						this.getNearbyStation(this.currentRadius);
						uni.hideLoading();
					},
					fail: (err) => {
						console.log("地图移动失败", err);
						// 失败时也更新UI
						this.updateUserLocationMarker();
						uni.hideLoading();
					}
				});

			},
			// 切换场站列表显示状态
			toggleStationList() {
				this.showStationList = !this.showStationList;
			},
			// 更新用户位置标记点
			updateUserLocationMarker() {
				this.userLocationMarker = {
					id: -1,
					latitude: this.latitude,
					longitude: this.longitude,
					iconPath: '/static/location@3x.png',
					width: 32,
					height: 32,
					anchor: {
						x: 0.5,
						y: 0.5
					}
				};

				// 更新地图标记点数组
				const newCovers = [this.userLocationMarker];
				// 保留原有的充电站标记点
				this.covers.slice(1).forEach(marker => {
					newCovers.push(marker);
				});
				this.covers = newCovers;
			},

			// 修改initLocation方法使用userLocation数据
			initLocation() {
				this.updateUserLocationMarker();
				this.getNearbyStation(this.currentRadius);
			},
			// 处理地图缩放变化
			handleScaleChange(e) {
				if (this.debounceTimer) {
					clearTimeout(this.debounceTimer);
				}

				this.debounceTimer = setTimeout(() => {
					if (e.type === 'end') {
						const newScale = e.detail.scale;
						console.log("地图缩放结束，当前缩放级别", newScale);

						// 计算动态半径
						const dynamicRadius = this.calculateDynamicRadius(newScale);
						console.log("计算后的搜索半径", dynamicRadius, "米");

						// 更新当前半径
						this.currentRadius = dynamicRadius;

						// 获取新半径范围内的充电站
						this.getNearbyStation(dynamicRadius);
					}
				}, 500); // 防抖延迟500ms
			},

			// 计算动态半径
			calculateDynamicRadius(scale) {
				console.log("当前级别", scale);
				let newScale = Math.floor(scale);
				console.log("取整后级别", newScale)
				// 从映射表中获取半径
				let radius = this.scaleRadiusMap[newScale];

				// 如果没有精确匹配，找到最接近的缩放级别
				if (radius === undefined) {
					const scales = Object.keys(this.scaleRadiusMap).map(Number).sort((a, b) => a - b);

					// 如果缩放级别大于最大定义级别，使用最小半径
					if (scale > scales[0]) {
						radius = this.scaleRadiusMap[scales[0]];
					}
					// 如果缩放级别小于最小定义级别，使用最大半径
					else if (scale < scales[scales.length - 1]) {
						radius = this.scaleRadiusMap[scales[scales.length - 1]];
					}
					// 在定义的级别之间，找到最近的两个级别进行插值
					else {
						for (let i = 0; i < scales.length - 1; i++) {
							if (scale <= scales[i] && scale > scales[i + 1]) {
								const ratio = (scale - scales[i + 1]) / (scales[i] - scales[i + 1]);
								radius = this.scaleRadiusMap[scales[i + 1]] +
									ratio * (this.scaleRadiusMap[scales[i]] - this.scaleRadiusMap[scales[i + 1]]);
								break;
							}
						}
					}
				}

				// 确保半径在最小和最大范围内
				radius = Math.max(this.minRadius, Math.min(this.maxRadius, radius));

				return Math.round(radius);
			},

			// 修改为接受半径参数
			getNearbyStation(radius) {
				const params = {
					longitude: this.longitude,
					latitude: this.latitude,
					radius: radius || this.currentRadius
				};

				uni.showLoading({
					title: '加载中...'
				});

				uni.request({
					url: this.$baseUrl + "/device_api/device/station/near",
					method: "GET",
					data: params,
					success: (res) => {
						uni.hideLoading();
						if (res.data && res.data.data) {
							this.stationList = res.data.data;
							this.updateMapMarkers();
						}
					},
					fail: (err) => {
						uni.hideLoading();
						console.error("获取充电站失败:", err);
						uni.showToast({
							title: '获取充电站失败',
							icon: 'error'
						});
					}
				});
			},

			// 更新地图标记点
			updateMapMarkers() {
				// 保留用户位置标记点
				const newCovers = this.userLocationMarker ? [this.userLocationMarker] : [];

				// 添加充电站标记点
				this.stationList.forEach((station, index) => {
					// 计算距离
					const distance = this.calculateDistance(
						this.latitude, this.longitude,
						station.stationLat, station.stationLng
					);

					//更新station对象的distance属性
					station.distance = (distance / 1000).toFixed(2);

					newCovers.push({
						id: index,
						latitude: station.stationLat,
						longitude: station.stationLng,
						iconPath: '/static/map_marker@2x.png',
						width: 32,
						height: 32,
						anchor: {
							x: 0.5,
							y: 1
						},
						callout: {
							content: station.stationName,
							color: '#333',
							fontSize: 12,
							borderRadius: 4,
							padding: 8,
							display: 'ALWAYS'
						}
					});
				});

				this.covers = newCovers;
			},

			//计算两点间距离(米) - 使用Haversine公式
			calculateDistance(lat1, lng1, lat2, lng2) {
				const R = 6371000; // 地球半径(米)
				const dLat = (lat2 - lat1) * Math.PI / 180;
				const dLng = (lng2 - lng1) * Math.PI / 180;
				const a =
					Math.sin(dLat / 2) * Math.sin(dLat / 2) +
					Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
					Math.sin(dLng / 2) * Math.sin(dLng / 2);
				const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
				return R * c;
			},

			//标记点点击事件等其他方法保持不变
			markertap(marker) {
				const markerId = marker.detail.markerId;
				if (markerId === -1) return;

				if (this.stationList[markerId]) {
					this.mapClickStation = this.stationList[markerId];
					this.isshow = true;
				}
			},

			stationClick(id) {
				if (!id) return;
				uni.navigateTo({
					url: `/pages/stationDetail/stationDetail?id=${id}`
				});
			}
		}
	}
</script>

<style lang="scss">
	page {
		height: 100%;
	}

	.container {
		display: flex;
		flex-direction: column;
		height: 100%;
	}

	/* 地图容器样式 */
	.map-container {
		width: 100%;
		height: 50vh;
		/* 地图占50%高度 */
	}

	/* 右下角控制按钮 */
	.map-controls {
		position: absolute;
		right: 20rpx;
		bottom: 20rpx;
		z-index: 99;
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 24rpx;

		.control-btn {
			width: 64rpx;
			height: 64rpx;
			background-color: #fff;
			border-radius: 50%;
			display: flex;
			align-items: center;
			justify-content: center;
			box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.15);

			cover-image {
				width: 32rpx;
				height: 32rpx;
			}
		}
	}

	/* 右上角列表按钮 */
	.list-btn-container {
		position: absolute;
		right: 20rpx;
		top: 20rpx;
		z-index: 99;

		.list-btn {
			width: 64rpx;
			height: 64rpx;
			background-color: #fff;
			border-radius: 50%;
			display: flex;
			align-items: center;
			justify-content: center;
			box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.15);

			cover-image {
				width: 32rpx;
				height: 32rpx;
			}
		}
	}

	/* 场站列表容器 */
	.station-list-container {
		flex: 1;
		background-color: #fff;
		border-top: 1px solid #f0f0f0;
		box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
		display: flex;
		flex-direction: column;
	}

	/* 列表头部 */
	.list-header {
		padding: 20rpx 30rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-bottom: 1px solid #f5f5f5;
		background-color: #fff;

		.list-title {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
		}

		.list-count {
			font-size: 26rpx;
			color: #999;
		}
	}

	/* 滚动区域 */
	.station-scroll {
		flex: 1;
		padding: 0 20rpx;
	}

	/* 场站列表 */
	.station-list {
		padding-bottom: 20rpx;
	}

	/* 单个场站项 */
	.station-item {
		background-color: #fff;
		border-radius: 16rpx;
		margin-top: 20rpx;
		padding: 24rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);

		.station-main {
			display: flex;
			justify-content: space-between;
			align-items: flex-start;
		}

		.station-info {
			flex: 1;
		}

		.station-name {
			font-size: 30rpx;
			font-weight: bold;
			color: #333;
			display: block;
			margin-bottom: 10rpx;
		}

		.station-address {
			font-size: 26rpx;
			color: #666;
			display: block;
			margin-bottom: 16rpx;
		}

		.station-tags {
			display: flex;
			flex-wrap: wrap;
			gap: 10rpx;

			.tag {
				font-size: 22rpx;
				color: #1DB3F3;
				background-color: #e6f7ff;
				padding: 4rpx 12rpx;
				border-radius: 6rpx;
			}
		}

		.station-distance {
			display: flex;
			align-items: center;

			.distance-value {
				font-size: 26rpx;
				color: #999;
				margin-right: 10rpx;
			}

			.nav-icon {
				width: 40rpx;
				height: 40rpx;
			}
		}

		.station-footer {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-top: 20rpx;
			padding-top: 20rpx;
			border-top: 1px dashed #eee;

			.price-text {
				font-size: 28rpx;
				color: #f40;
				font-weight: bold;
			}

			.status-text {
				font-size: 26rpx;
				color: #1DB3F3;
			}
		}
	}

	/* 弹窗内容样式 */
	.popup-content {
		width: 100%;
		height: 100%;
		padding: 24rpx;
		box-sizing: border-box;

		.station-info {
			display: flex;
			align-items: center;

			.station-icon {
				width: 120rpx;
				height: 120rpx;
				margin-right: 24rpx;
				flex-shrink: 0;
			}

			.info-detail {
				flex: 1;

				.station-name {
					display: flex;
					justify-content: space-between;
					align-items: center;

					>cover-view:first-child {
						font-size: 32rpx;
						font-weight: bold;
						color: #333;
						max-width: 60%;
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;
					}

					.price {
						color: #0091FF;
						font-size: 28rpx;
					}
				}

				.line-space {
					height: 24rpx;
				}

				.station-meta {
					display: flex;
					justify-content: space-between;
					align-items: center;

					.distance {
						display: flex;
						align-items: center;

						.map-icon {
							width: 36rpx;
							height: 36rpx;
							margin-right: 8rpx;
						}

						text {
							color: #999;
							font-size: 26rpx;
						}
					}

					.go-charging {
						background-color: #1DB3F3;
						width: 140rpx;
						height: 60rpx;
						border-radius: 30rpx;
						color: #fff;
						font-size: 28rpx;
						display: flex;
						align-items: center;
						justify-content: center;
					}
				}
			}
		}
	}

	/* 关闭按钮样式 */
	.close-btn {
		width: 60rpx;
		height: 60rpx;
		background-color: rgba(0, 0, 0, 0.5);
		color: #fff;
		line-height: 60rpx;
		text-align: center;
		border-radius: 50%;
		position: absolute;
		bottom: -100rpx;
		left: 50%;
		transform: translateX(-50%);
		font-size: 36rpx;
	}
</style>